package com.apes.fn.controlWaitDisposal;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.productReceive.ProductReceiveItemRepository;
import com.apes.fn.server.productReceive.ProductReceiveRepository;
import com.apes.fn.server.servicePlan.model.ServicePlan;
import com.apes.fn.server.servicePlan.repository.ServicePlanRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxEventService;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.util.DistributedLock;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.product.model.ServeType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: apes-server
 * @description 总控待处理
 * @author: czs
 * @create: 2021-05-16 16:45
 **/
@Service("controlWaitDisposalService")
public class ControlWaitDisposalService extends DomainService {
    @Autowired
    ServicePlanRepository servicePlanRepository;
    @Autowired
    DeptRepository deptRepository;
    @Autowired
    ProductReceiveItemRepository productReceiveItemRepository;
    @Autowired
    ProductReceiveRepository productReceiveRepository;
    @Autowired
    ControlWaitDisposalDao controlWaitDisposalDao;

    @Autowired
    private DistributedLock distributedLock;

    private final WaitSubmissionRepository waitSubmissionRepository;
    private final OutboxEventService outboxEventService;
    public ControlWaitDisposalService(WaitSubmissionRepository repository, OutboxEventService outboxEventService) {
        this.waitSubmissionRepository = repository;
        this.outboxEventService = outboxEventService;
    }


    @OutboxSubscriber(name = "车辆服务信息：服务方案",condition = " confirmDate == null ")
    public void subscribeServicePlan(ServicePlan servicePlan) {
        createWaitSubmission(servicePlan);
    }

    /**
     * 创建未提交方案或删除提交方案
     * @param servicePlan
     */
    private void createWaitSubmission(ServicePlan servicePlan) {
        WaitSubmission one = waitSubmissionRepository.findOne(servicePlan.getId());
        WaitSubmission waitSubmission = one==null? new WaitSubmission():one;
        waitSubmission.setId(servicePlan.getId());
        waitSubmission.setBelongDept(servicePlan.getBelongDept());
        waitSubmission.setCarLicense(servicePlan.getFnCustomerExpand().getCarLicense());
        waitSubmission.setSalesAmount(servicePlan.getSalesAmount());
        waitSubmission.setState(servicePlan.getState());
        waitSubmission.setServeTypeName(findServeType(servicePlan));
        waitSubmission.setPlanCreateDate(servicePlan.getCreateDate());
        if (checkState(servicePlan.getState())){
            waitSubmission.setValid(true);
        }else {
            waitSubmission.setValid(false);
        }
        waitSubmissionRepository.save(waitSubmission);
    }
    private boolean checkState(String state){
        switch (state){
            case "techAudit":
            case "create":
            case "backTechAudit":
            case "priceAudit":
            case "backPriceAudit":
            case "inquiryFinish":
            case "backInquiry":
            return true;
            default:return false;
        }
    }


    /**
     * 查找方案下的服务类型
     * @param servicePlan
     * @return
     */
    private String findServeType(ServicePlan servicePlan) {
        StringBuffer sf = new StringBuffer();
        Map<String,String> map = new HashMap();
        servicePlan.getServicePlanItems().forEach(servicePlanItem -> {
            ServeType serveType = servicePlanItem.getServeType();
            if (map.get(serveType.getId())==null){
                map.put(serveType.getId(),serveType.getName());
                sf.append(serveType.getName()+",");
            }
        });
        sf.append(" ");
        return sf.toString();
    }


    public JSONArray findAllWait(SimpleRequest request){
        JSONArray array = new JSONArray();
            String[] strList = new String[] {"待提交方案","待配件领用单"};
            String[] sqlList = new String[] {"WAIT_SUBMISSION","WAIT_RECEIVE"};
            String belongDeptId = request.get("dept_id");
            Dept dept = deptRepository.findOne(belongDeptId);
            for (int i = 0; i < strList.length; i++) {
                JSONObject singleItem = new JSONObject();
                singleItem.put("LEFTTEXT", strList[i]);
                List<Map> resultList = null;
                if(dept==null)throw new RuntimeException("暂无当前部门");
                switch (i){
                    case 0:
                        resultList = waitSubmissionRepository.queryWaitSubmission(dept.getId());
                        singleItem.put("formId", "fn.controlWaitDisposalService.findAllPlan");
                        break;
                    case 1:
                        resultList = servicePlanRepository.queryWaitReceive(dept.getId());
                        singleItem.put("formId", "fn.controlWaitDisposalService.findAllReceive");
                        break;
                        default:
                            break;
                }
                singleItem.put("RIGHTTEXT", Integer.parseInt(resultList.get(0).get(sqlList[i]).toString()));
                singleItem.put("dept_id", belongDeptId);

                array.add(singleItem);
        }
        return array;


    }

    /**
     * 查询做单部门的待提交方案
     * @param request
     * @return
     */
    public Page<Object> findAllWaitSubmission(SimpleRequest request){
        JSONObject re = request.getJO();
        JSONArray waitSubmission = controlWaitDisposalDao.findWaitSubmission(re);
        Pageable pageable = PageRequest.of(((Integer) request.get("page")) - 1, request.get("size"));
        if (waitSubmission.size() != 0) {
            int total = waitSubmission.size();
            PageImpl<Object> pPage = new PageImpl(waitSubmission, pageable, waitSubmission.size() == 0 ? 0 : total);
            return pPage;
        }
       return new PageImpl(waitSubmission, pageable, waitSubmission.size() == 0 ? 0 : 0);
    }

    /**
     * 查询做单部门的待配件领用
     * @param request
     * @return
     */
    public Page<Object> findAllWaitReceive(SimpleRequest request){
        JSONObject re = request.getJO();
        JSONArray waitReceive = controlWaitDisposalDao.findAllWaitReceive(re);
        Pageable pageable = PageRequest.of(((Integer) request.get("page")) - 1, request.get("size"));
        if (waitReceive.size() != 0) {
            int total = waitReceive.size();
            PageImpl<Object> pPage = new PageImpl(waitReceive, pageable, waitReceive.size() == 0 ? 0 : total);
            return pPage;
        }
        return new PageImpl(waitReceive, pageable, waitReceive.size() == 0 ? 0 : 0);
    }


}
